#include "MainForm.h"
#include "MySence.h"
#include <time.h>
#include "platform.h"
#include "sqlite3.h"
#include "encoding.h"
#include "def.h"
using namespace cocos2d;


static CCPoint s_tCurPos = CCPointZero;
static float overFlowHeight = 0;
static float fontScale = 1; // windows 320*480 是实际分辨率640*960的 1/2  真机应改为1

static int charsPreLine = 3*4; //UTF-8下每个汉字是3个字节 中英混排换行判断可能会出现半个字 所有应在数据输入时添加换行符

static long interTime = 0; //记录双击的时间间隔 通过2次endTime判断
static long clickTime = 0; //上次单击的结束时间
static bool dbClicked = false; 

CCSprite* sps[max_rows][line_count]={NULL};

CCLabelTTF* lbs[max_rows][line_count]={NULL};

MainForm::MainForm()
{
	setIsTouchEnabled( true );

	int ret = 0;
	sqlite3 *db = NULL;
	sqlite3_stmt *stmt;
    
	ret = sqlite3_open(getdbfile(), &db);
	//ret = sqlite3_open(dbfile, &db);
	//CCLog("ret = %d",ret);
    
    
	/*char * msg = NULL;
     char * sql = "create table if not exists messages (msgid integer PRIMARY KEY autoincrement, msgtext TEXT  NULL,synflag  integer DEFAULT 0 NULL)";
     ret = sqlite3_exec(db, sql, NULL, NULL, &msg);
     CCLog("crate table[%s]",sql);
     CCLog("sqlite3_open ret=%d msg=%s",ret,msg);*/
    
    
	ret = sqlite3_prepare(db,"select * from messages",-1,&stmt,0);
	//CCLog("ret = %d",ret);
    
	int rc = sqlite3_step(stmt);
	//CCLog("rc = %d",rc);
    
	
    
	CCSpriteBatchNode *spriteBatch=CCSpriteBatchNode::batchNodeWithFile("a.png");  
	this->addChild(spriteBatch);  
	CCSpriteFrameCache::sharedSpriteFrameCache()->addSpriteFramesWithFile("a.plist"); 
    
	int n=0;
	int maxRow = 0;
	while( rc  == SQLITE_ROW ){
        
		int msgid = sqlite3_column_int(stmt,0);
		const unsigned char *mm = sqlite3_column_text(stmt,1);
		int delflag = sqlite3_column_int(stmt,2);
        
		CCSize size = CCDirector::sharedDirector()->getWinSize();
		float H = size.height;
		float W = size.width;
        
		int row = n/line_count;
		int colum = n%line_count;
        
		maxRow = row;
        
		float center_w = (0.5 + colum)*cell_width*scale;
		//float center_h = H - (0.5+row)*cell_height*scale-menu_height*menuscale; //with top bar
		float center_h = H - (0.5+row)*cell_height*scale;
        
		
		//CCSprite* pSprite = CCSprite::spriteWithFile("a.png");
		
		CCSprite *pSprite=CCSprite::spriteWithSpriteFrameName(delflag==1?"b.png":"a.png"); 
		pSprite->setScale(scale);
        
		pSprite->setPosition( ccp(center_w, center_h) );
		this->addChild(pSprite, 0);
        
        
		
        
		CCLabelTTF* pLabel = CCLabelTTF::labelWithString((const char*)mm, fontName, fontSize);
		
		//delete mmNew;
		pLabel->setColor(ccc3(100, 50, 50));
		pLabel->setPosition( ccp(center_w, center_h-fontSize/3) );
		
		this->addChild(pLabel, 1);
        
		void* userdata = (void *)msgid;
		pSprite->setUserData(userdata);
		sps[row][colum] = pSprite;
		lbs[row][colum] = pLabel;
        
		n++;
		rc=sqlite3_step(stmt);
	}
	overFlowHeight = (maxRow + 1) * cell_height*(scale) - win_height;
	if( overFlowHeight < 0){
		overFlowHeight = 0;
	}

    sqlite3_reset(stmt);
	sqlite3_finalize(stmt);
	sqlite3_close(db);
    
	CCPoint curPos  = this->getPosition();
	//CCLog("MainForm x=%f,y=%f",curPos.x,curPos.y);
}

void MainForm::ccTouchesEnded(CCSet* touches, CCEvent* event)
{
	
	long timeNow = millisecondNow();
	if( clickTime == 0){
		clickTime = timeNow;
		dbClicked = false;
	}else{
		interTime = timeNow-clickTime;
		if(interTime > 200 ){
			clickTime = timeNow;
			dbClicked = false;
		}else{
			clickTime = 0;
			dbClicked = true;
		}
	}
    
	if(!dbClicked) {
		return;
	}
   // CCLog("MainForm dbclicked trigerred");

	
	CCSetIterator it;
	CCTouch* touch;
    
	for( it = touches->begin(); it != touches->end(); it++) 
	{
		touch = (CCTouch*)(*it);
		if(!touch){
			break;
		}
        
		CCPoint location = touch->locationInView(touch->view());
		location = CCDirector::sharedDirector()->convertToGL(location);
		CCSize s = CCDirector::sharedDirector()->getWinSize();
        
		int j,i;
		j = ((int)(location.x)) / ((int)(cell_width*scale));
		//i = ((int)(s.height-menu_height*menuscale-location.y+s_tCurPos.y))/((int)(cell_height*scale)); //with top bar
		i = ((int)(s.height-location.y+s_tCurPos.y))/((int)(cell_height*scale)); 
        
		//CCLog("--location.y=%f--------",location.y);
		//return;
		if( i < max_rows && j< line_count)
		{
			//CCLog("--i:%d--------",i);
			CCSprite* pSprite = sps[i][j];
			if( pSprite != NULL)
			{
				//CCLog("--j:%d--------",j);
				void * userData = pSprite->getUserData();
				if( userData == NULL) return;
				
				int msgid = (int)(userData);
				//sps[i][j] = NULL;
				sqlite3 *pDB = NULL;
				char * msg = NULL;
				int ret;
				
				ret = sqlite3_open(getdbfile(), &pDB);

				char sel[100] = {'\0'};
				char *selfmt = "select synflag from messages where msgid=%d";
				sprintf(sel,selfmt,msgid);
				sqlite3_stmt *stmt;
				ret = sqlite3_prepare(pDB,sel,-1,&stmt,0);
				sqlite3_step(stmt);
				int synflg = sqlite3_column_int(stmt,0);
				//CCLog("-synflg=%d--------",synflg);
				sqlite3_reset(stmt);//必须reset下次才能使用

				char sql[100] = {'\0'};
				char * fmt = "update messages set synflag=%d where msgid=%d";
				sprintf(sql,fmt,1-synflg,msgid);
				ret = sqlite3_exec(pDB, sql, NULL, NULL, &msg);
				
				sqlite3_close(pDB);
				

				
				//pSprite->setIsVisible(false);
				//lbs[i][j]->setIsVisible(false);
				

				CCSpriteFrame *frame=CCSpriteFrameCache::sharedSpriteFrameCache()->spriteFrameByName((1-synflg)==1?"b.png":"a.png");  
				//CCSpriteFrame *frame=CCSpriteFrameCache::sharedSpriteFrameCache()->spriteFrameByName("a.png"); 

				pSprite->setDisplayFrame(frame); 
			}
		}
	}
    
	
	
}

void MainForm::ccTouchesBegan(CCSet *pTouches, CCEvent *pEvent)
{
	CCSetIterator it = pTouches->begin();
    CCTouch* touch = (CCTouch*)(*it);
    
    m_tBeginPos = touch->locationInView( touch->view() );	
    m_tBeginPos = CCDirector::sharedDirector()->convertToGL( m_tBeginPos );
}

void MainForm::ccTouchesMoved(CCSet *pTouches, CCEvent *pEvent)
{
	clickTime=0;

	CCSetIterator it = pTouches->begin();
    CCTouch* touch = (CCTouch*)(*it);
    
    CCPoint touchLocation = touch->locationInView( touch->view() );	
    touchLocation = CCDirector::sharedDirector()->convertToGL( touchLocation );
    float nMoveY = touchLocation.y - m_tBeginPos.y;
    

	//整个屏幕+屏幕下方的溢出部分构成整个场景 场景左下角为0点
    CCPoint curPos  = this->getPosition();
    CCPoint nextPos = ccp(curPos.x, curPos.y + nMoveY);
    CCSize winSize = CCDirector::sharedDirector()->getWinSize();
    
	//MainForm这个层 已经下移到场景的最底端
	if (nextPos.y < 0.0f){this->setPosition(CCPointZero);return;}

	//MainForm这个层的最底端已经移动到了溢出部分的上面（及已经出现在了屏幕上）停止上移
    if (nextPos.y > overFlowHeight+menu_height*scale){return;}
    
    this->setPosition(nextPos);
    m_tBeginPos = touchLocation;
    s_tCurPos   = nextPos;
	//CCLog("MainForm x=%f,y=%f",curPos1.x,curPos1.y);
    
}


long MainForm::millisecondNow()  
{ 
	struct cocos2d::cc_timeval now;
    cocos2d::CCTime::gettimeofdayCocos2d(&now, NULL);    
    return (now.tv_sec * 1000 + now.tv_usec /1000.0);
}

